import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(getToken())
  const userInfo = ref(null)
  const permissions = ref([])
  const roles = ref([])
  const preferences = ref({
    theme: 'light',
    language: 'zh-CN',
    notifications: {
      email: true,
      push: true,
      sms: false
    },
    privacy: {
      showProfile: true,
      showProgress: true,
      showAchievements: true
    }
  })

  // 学习数据
  const learningStats = ref({
    totalStudyTime: 0,
    coursesCompleted: 0,
    examsCompleted: 0,
    problemsSolved: 0,
    articlesRead: 0,
    notesCreated: 0,
    currentStreak: 0,
    longestStreak: 0
  })

  // 成就数据
  const achievements = ref([])
  const badges = ref([])

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!userInfo.value)
  const userName = computed(() => userInfo.value?.username || '')
  const userAvatar = computed(() => userInfo.value?.avatar || '/default-avatar.png')
  const userEmail = computed(() => userInfo.value?.email || '')
  const userLevel = computed(() => {
    const totalPoints = learningStats.value.coursesCompleted * 100 + 
                       learningStats.value.examsCompleted * 50 + 
                       learningStats.value.problemsSolved * 20
    if (totalPoints < 500) return { level: 1, name: '初学者', color: '#909399' }
    if (totalPoints < 1500) return { level: 2, name: '学习者', color: '#409EFF' }
    if (totalPoints < 3000) return { level: 3, name: '进阶者', color: '#67C23A' }
    if (totalPoints < 5000) return { level: 4, name: '专家', color: '#E6A23C' }
    return { level: 5, name: '大师', color: '#F56C6C' }
  })

  const hasPermission = computed(() => (permission) => {
    return permissions.value.includes(permission)
  })

  const hasRole = computed(() => (role) => {
    return roles.value.includes(role)
  })

  // 方法
  const login = async (loginForm) => {
    try {
      // 根据登录类型选择不同的API
      let response
      if (loginForm.verificationCode) {
        // 使用验证码登录
        response = await userApi.login({
          username: loginForm.username,
          password: loginForm.password,
          verificationCode: loginForm.verificationCode
        })
      } else {
        // 简单登录（测试用）
        response = await userApi.simpleLogin({
          username: loginForm.username,
          password: loginForm.password
        })
      }

      // 后端返回格式: { code: 200, msg: "success", data: UserVO }
      if (response.code === 200 && response.data) {
        const user = response.data

        // 生成临时token（实际项目中应该从后端获取）
        const newToken = `token_${user.id}_${Date.now()}`

        token.value = newToken
        userInfo.value = user
        setToken(newToken)

        // 获取用户权限和角色
        try {
          await getUserPermissions()
          await getUserLearningStats()
        } catch (error) {
          console.warn('获取用户额外信息失败:', error)
        }

        return response
      } else {
        throw new Error(response.msg || '登录失败')
      }
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }

  /**
   * 登录成功后获取用户信息
   * 适用于使用API直接登录后获取用户信息
   */
  const fetchUserInfo = async () => {
    try {
      const response = await userApi.getUserInfo()
      
      if (response.code === 200 && response.data) {
        userInfo.value = response.data
        
        // 设置token（如果后端没有返回token，这里使用一个临时值）
        if (!token.value) {
          const newToken = `token_${response.data.id}_${Date.now()}`
          token.value = newToken
          setToken(newToken)
        }
        
        // 获取用户权限和角色
        try {
          await getUserPermissions()
          await getUserLearningStats()
        } catch (error) {
          console.warn('获取用户额外信息失败:', error)
        }
        
        return response.data
      } else {
        throw new Error(response.msg || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  /**
   * 直接设置用户信息，用于登录后直接使用返回的用户信息
   */
  const setUserInfo = async (user) => {
    try {
      if (!user || !user.id) {
        throw new Error('无效的用户信息')
      }
      
      // 设置用户信息
      userInfo.value = user
      
      // 持久化存储用户信息
      localStorage.setItem('zenithmind_user_info', JSON.stringify(user))
      
      // 生成并设置token
      const newToken = `token_${user.id}_${Date.now()}`
      token.value = newToken
      setToken(newToken, true) // 设置为记住我模式，保持登录状态
      
      return user
    } catch (error) {
      console.error('设置用户信息失败:', error)
      throw error
    }
  }

  const register = async (registerForm) => {
    try {
      const response = await userApi.register({
        username: registerForm.username,
        email: registerForm.email,
        password: registerForm.password,
        code: registerForm.code // 后端期望的字段名是code
      })

      // 后端返回格式: { code: 200, msg: "success", data: UserVO }
      if (response.code === 200) {
        return response
      } else {
        throw new Error(response.msg || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  const logout = async () => {
    try {
      if (token.value) {
        await userApi.logout()
      }
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      token.value = null
      userInfo.value = null
      permissions.value = []
      roles.value = []
      removeToken()
    }
  }

  const getUserInfo = async () => {
    try {
      if (!token.value) return null

      const response = await userApi.getUserInfo()

      // 后端返回格式: { code: 200, msg: "success", data: UserVO }
      if (response.code === 200 && response.data) {
        userInfo.value = response.data
        return response.data
      } else {
        throw new Error(response.msg || '获取用户信息失败')
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果获取用户信息失败，可能是token过期，清除登录状态
      await logout()
      throw error
    }
  }

  const updateUserInfo = async (updateData) => {
    try {
      const response = await userApi.updateUserInfo(updateData)
      userInfo.value = { ...userInfo.value, ...response.data }
      return response
    } catch (error) {
      console.error('更新用户信息失败:', error)
      throw error
    }
  }

  const updatePassword = async (passwordData) => {
    try {
      const response = await userApi.updatePassword(passwordData)
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      throw error
    }
  }

  const uploadAvatar = async (file) => {
    try {
      const response = await userApi.uploadAvatar(file)
      userInfo.value.avatar = response.data.avatar
      return response
    } catch (error) {
      console.error('上传头像失败:', error)
      throw error
    }
  }

  const getUserPermissions = async () => {
    try {
      const response = await userApi.getUserPermissions()
      permissions.value = response.data.permissions || []
      roles.value = response.data.roles || []
      return response.data
    } catch (error) {
      console.error('获取用户权限失败:', error)
      throw error
    }
  }

  const getUserLearningStats = async () => {
    try {
      const response = await userApi.getLearningStats()
      learningStats.value = { ...learningStats.value, ...response.data }
      return response.data
    } catch (error) {
      console.error('获取学习统计失败:', error)
      throw error
    }
  }

  const getUserAchievements = async () => {
    try {
      const response = await userApi.getAchievements()
      achievements.value = response.data.achievements || []
      badges.value = response.data.badges || []
      return response.data
    } catch (error) {
      console.error('获取成就数据失败:', error)
      throw error
    }
  }

  const updatePreferences = async (newPreferences) => {
    try {
      const response = await userApi.updatePreferences(newPreferences)
      preferences.value = { ...preferences.value, ...newPreferences }
      
      // 保存到本地存储
      localStorage.setItem('userPreferences', JSON.stringify(preferences.value))
      
      return response
    } catch (error) {
      console.error('更新用户偏好失败:', error)
      throw error
    }
  }

  const recordStudyTime = async (duration, courseId) => {
    try {
      const response = await userApi.recordStudyTime({ duration, courseId })
      learningStats.value.totalStudyTime += duration
      return response
    } catch (error) {
      console.error('记录学习时间失败:', error)
      throw error
    }
  }

  const checkIn = async () => {
    try {
      const response = await userApi.checkIn()
      learningStats.value.currentStreak = response.data.currentStreak
      learningStats.value.longestStreak = response.data.longestStreak
      return response
    } catch (error) {
      console.error('签到失败:', error)
      throw error
    }
  }

  const initUser = async () => {
    try {
      if (token.value) {
        await getUserInfo()
        await getUserPermissions()
        await getUserLearningStats()
        await getUserAchievements()
        
        // 从本地存储恢复偏好设置
        const savedPreferences = localStorage.getItem('userPreferences')
        if (savedPreferences) {
          preferences.value = { ...preferences.value, ...JSON.parse(savedPreferences) }
        }
      }
    } catch (error) {
      console.error('初始化用户失败:', error)
      // 如果初始化失败，清除登录状态
      await logout()
    }
  }

  const refreshUserData = async () => {
    try {
      if (isLoggedIn.value) {
        await Promise.all([
          getUserInfo(),
          getUserLearningStats(),
          getUserAchievements()
        ])
      }
    } catch (error) {
      console.error('刷新用户数据失败:', error)
    }
  }

  return {
    // 状态
    token,
    userInfo,
    permissions,
    roles,
    preferences,
    learningStats,
    achievements,
    badges,
    
    // 计算属性
    isLoggedIn,
    userName,
    userAvatar,
    userEmail,
    userLevel,
    hasPermission,
    hasRole,
    
    // 方法
    login,
    register,
    logout,
    getUserInfo,
    updateUserInfo,
    updatePassword,
    uploadAvatar,
    getUserPermissions,
    getUserLearningStats,
    getUserAchievements,
    updatePreferences,
    recordStudyTime,
    checkIn,
    initUser,
    refreshUserData,
    fetchUserInfo,
    setUserInfo
  }
})
